import React, {
  useEffect,
  useContext,
  useMemo,
  useState,
  useCallback,
  useRef,
  ReactText,
} from 'react';
import {
  Form,
  Button,
  Divider,
  Pagination,
  message,
  Row,
  Col,
  Modal,
  Spin,
  Tooltip,
  Select as AntdSelect,
} from 'antd';
import { useForm } from 'antd/lib/form/Form';
import { InspectorContext } from '../FlowManage';
import { IntentionLibraryInfo } from '../../schema/IntentionLibrary';
import {
  createIntention,
  getInterfacesList,
  getWebInterface,
  getSmsTempList,
  getSmsTempInfo,
  getIntentionsAll,
  getFlowGlobalSet,
} from '../../servers/servers';

import {
  PlusOutlined,
  SettingOutlined,
  EditOutlined,
  DeleteOutlined,
  MinusCircleOutlined,
  PlusCircleOutlined,
  QuestionCircleFilled,
} from '@ant-design/icons';
import { InterfacesInfo } from '../../schema/BasicResource';
import './IntentComponent.scss';
import {
  FetchDataParam,
  FetchDataResponse,
  FetchRecordResponse,
  PageSelect,
} from 'components/UILibrary/pageSelect';

import { verifyNull } from 'utils/tools';
import { GlobalNotUnderstood } from '../FlowGlobalSet/components/GlobalNotUnderstood';
import { GlobalTimeout } from '../FlowGlobalSet/components/GlobalTimeout';
import { CustomFormItemsHoc } from './CustomFormHoc';
import { cloneDeep, debounce } from 'lodash';

/**
 * 意图组件
 * 示例： AI管理-机器人管理-版本管理-配置话术流程-意图组件
 */
const IntentComponent: React.FC = () => {
  const [form] = useForm();
  const [formInterface] = useForm();
  // 上下文-数据
  const { versionId, selectedData, onInputChange, nodeDataArray, onRemoveLink, isView } =
    useContext(InspectorContext);

  const { Input, TextArea, Switch, InputNumber, Select, Option } = CustomFormItemsHoc({
    disabled: isView,
  });

  /**短信开关 */
  const smsSelectRef = useRef<any>();

  // 【全局设置】,默认：没有配置为0，有配置时最小为1
  const [maxNotUnderstood, setMaxNotUnderstood] = useState(0);
  const [maxTimeout, setMaxTimeout] = useState(0);
  // 全局配置
  const [globalset, setGlobalset] = useState<any>(undefined);

  /**意图相关 */
  // 意图当前页码
  const [current, setCurrent] = useState<number>(1);
  // 意图每页条数
  const pageSize = 6;
  // 意图数据总数
  const [total, setTotal] = useState<number>(0);
  // 意图Table数据
  const [intentionList, setIntentionList] = useState<IntentionLibraryInfo[]>([]);
  // 意图搜索内容
  const [searchText, setSearchText] = useState<string>('');
  // 点击意图的index
  const [intentionIndex, setIntentionIndex] = useState<number | null>(null);
  // 点击意图的index，intentionContent存储意图相关信息
  const [intentionContent, setIntentionContent] = useState<any>({});
  /**意图数组clone，页面表单用：将字段名改为value和label对应值用于select */
  const intentionArrayItem = cloneDeep(selectedData.intentionArray).map((item: any) => {
    return {
      value: item.intentionId,
      label: item.text,
      interfaceInfo: item.interfaceInfo || null,
    };
  });

  /**接口相关 */
  // 接口搜索内容
  const [searchTextInterface, setSearchTextInterface] = useState<string>('');
  // 接口选择loading状态
  const [selecting, setSelecting] = useState<boolean>(false);
  // 接口当前页码
  const [currentInterface, setCurrentInterface] = useState<number>(1);
  // 接口每页条数
  const pageSizeInterface = 6;
  // 接口数据总数
  const [totalInterface, setTotalInterface] = useState<number>(15);
  // 接口Table数据
  const [interfacesList, setInterfacesList] = useState<InterfacesInfo[]>([]);

  /**当前选中的接口名 */
  const selectedIntentionName = useMemo(() => {
    if (
      typeof intentionIndex === 'number' &&
      intentionContent &&
      intentionContent['interfaceInfo']
    ) {
      return intentionContent['interfaceInfo']['name'];
    } else {
      return '';
    }
  }, [intentionContent, intentionIndex]);

  /**
   * 意图数据加载
   */
  const initIntentions = useCallback(async () => {
    try {
      const res = await getIntentionsAll({
        pageNo: current,
        pageSize,
        versionId,
        intentionName: searchText,
      });
      if (res.code === 0) {
        setIntentionList(res.data || []);
        setTotal(Number(res.count) || 1); // 备注：此处列表‘暂无数据’保留翻页数据，和其他地方处理方案不同，方便点击翻页，清空输入的搜索文字
        // sessionStorage.setItem('intentionIdyitu', JSON.stringify(res.data));
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }, [current, pageSize, versionId, searchText]);

  /**全局设置-加载 */
  const initFlowGlobalSet = useCallback(async () => {
    if (globalset) {
      return;
    }
    try {
      const {
        data: { globalNotUnderstood, globalTimeout },
      } = await getFlowGlobalSet({
        versionId,
      });
      setMaxNotUnderstood((globalNotUnderstood.notUnderstoodScripts?.length || 0) + 1);
      setMaxTimeout((globalTimeout.timeoutScripts?.length || 0) + 1);
      setGlobalset({ globalNotUnderstood, globalTimeout });
      form.setFieldsValue({ globalNotUnderstood, globalTimeout });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }, [form, globalset, versionId]);

  /**
   * 接口-数据加载
   */
  const initInterfaceList = useCallback(async () => {
    try {
      const res = await getInterfacesList({
        pageNo: currentInterface,
        pageSize: pageSizeInterface,
        versionId,
        interfaceName: searchTextInterface,
      });
      if (res.code === 0) {
        setInterfacesList(res.data || []);
        setTotalInterface(Number(res.count) || 0);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }, [currentInterface, searchTextInterface, versionId]);

  // 数据初始化 && 数据更新
  useEffect(() => {
    // 互相依赖
    initIntentions();
    initInterfaceList();
  }, [initIntentions, initInterfaceList]);

  useEffect(() => {
    console.log('✅form赋值并验证-意图组件-selectedData', selectedData);
    form.setFieldsValue(selectedData);
    setTimeout(() => {
      // 表单验证
      form.validateFields();
    }, 0);
  }, [form, selectedData]);

  useEffect(() => {
    if (selectedData.smsTemplateId) {
      // 短信id-回显
      smsSelectRef.current?.setValue(selectedData.smsTemplateId);
    }
  }, [selectedData.smsTemplateId]);

  useEffect(() => {
    if (
      selectedData.useGlobalNotUnderstoodSwitch === 'on' ||
      selectedData.useGlobalTimeoutSwitch === 'on'
    ) {
      // 全局设置-回显
      initFlowGlobalSet();
    }
  }, [
    initFlowGlobalSet,
    selectedData.useGlobalNotUnderstoodSwitch,
    selectedData.useGlobalTimeoutSwitch,
  ]);

  /**
   * 新增意图
   */
  const addItem = async (intentionName: string) => {
    // console.log("添加意图", intentionName);
    if (!intentionName) return;
    try {
      const res = await createIntention({
        intentionName,
        versionId,
      });
      if (res.code === 0) {
        message.success(`添加成功`);
        /**意图数组：将字段名改为intentionId和text */
        const arr = cloneDeep(selectedData.intentionArray);
        arr.push({
          text: intentionName,
          intentionId: res.data.intentionId,
          interfaceInfo: null,
        });
        onInputChange('intentionArray', arr, true);
        intentionArrayItem.push({
          vulue: res.data.intentionId,
          label: intentionName,
          interfaceInfo: null,
        });
        console.log('intentionArrayItem>>>>>>>>>>>>', intentionArrayItem);
        // 更新form显示
        form.setFieldsValue({
          intentionArrayItem,
        });
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  /**删除意图item的interfaceInfo */
  const deleteInterfaceInfo = (index: number) => {
    const arr = cloneDeep(selectedData.intentionArray);
    arr[index]['interfaceInfo'] = null;
    onInputChange('intentionArray', arr, true);
  };

  /**点击意图item按钮 */
  const handleClickIntentionItem = (index: number) => {
    setIntentionIndex(index);
    setIntentionContent(intentionArrayItem[index]);
    // 接口信息form表单赋值
    formInterface.setFieldsValue(intentionArrayItem[index]);
  };

  /**通过接口id查接口信息 */
  const getInterfaceInfo = async (interfaceId: number) => {
    setSelecting(true);
    try {
      const res = await getWebInterface({
        interfaceId,
      });
      // console.log("getInterfaceInfo -> res", res);
      if (res.code === 0) {
        const {
          interfaceName = '',
          callMode = 'get',
          url = '',
          requestParams,
          responseParams,
        } = res.data;

        // [{"interfaceParam":"name","internalParam":"张三"}] => [{"key":"name","value":"张三"}]
        let requestParam: any = [];
        if (requestParams && requestParams.length) {
          requestParam = requestParams.map(item => {
            return { key: item.interfaceParam, value: item.internalParam };
          });
        }
        // console.log("getInterfaceInfo -> requestParam", requestParam);

        // [{"interfaceParam":"name","internalParam":"张三"}] => [{"key":"name","value":"张三"}]
        let responseParam: any = [];
        if (responseParams && responseParams.length) {
          responseParam = responseParams.map(item => {
            return { key: item.interfaceParam, value: item.internalParam };
          });
        }
        // console.log("getInterfaceInfo -> responseParam", responseParam);

        const interfaceInfo = {
          interfaceId: interfaceId,
          name: interfaceName,
          method: callMode,
          /**接口地址 */
          url: url,
          requestParam: requestParam,
          // requestParam: [],
          responseParam: responseParam,
        };
        setIntentionContent({ ...intentionContent, ...{ interfaceInfo } });
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setSelecting(false);
  };

  /**
   * 查找短信模板的dataProvider
   */
  const fetchSmsTempList = (args: FetchDataParam): FetchDataResponse => {
    return new Promise(resolve => {
      getSmsTempList({
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        templateName: args.keywords,
      })
        .then(res => {
          resolve({
            data: res.data?.map(item => {
              return {
                label: item.templateName,
                value: item.templateId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };
  /**
   * pageSelect setValue时查记录的函数:根据id
   */
  const fetchSmsTempRecord = (templateId: ReactText): FetchRecordResponse => {
    return new Promise(resolve => {
      getSmsTempInfo(templateId as number)
        .then(res => {
          const item = res.data;
          resolve({
            label: item.templateName,
            value: item.templateId,
            data: item, // 便于onChange判断，有data则回显赋值不用更新数据
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };

  return (
    <>
      <Form
        layout="vertical"
        form={form}
        initialValues={{
          intentionArrayItem: intentionArrayItem,
          timeoutFollowUpStateVal: 5,
          timeoutScriptArray: [],
          notUnderstoodScriptArray: [],
        }}
      >
        <Form.Item
          label="意图组件名称"
          name="title"
          rules={verifyNull('请输入意图组件名称')}
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
        >
          <Input
            maxLength={25}
            onBlur={(e: { target: { value: any }; type: string }) => {
              onInputChange('title', e.target.value, e.type === 'blur');
            }}
          />
        </Form.Item>
        <Form.Item
          label="话术内容"
          name="script"
          rules={[
            {
              required: true,
              whitespace: true,
              max: 500,
              message: '仅支持输入500个以内字符',
            },
          ]}
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
        >
          <TextArea
            maxLength={500}
            onBlur={(e: { target: { value: any }; type: string }) => {
              onInputChange('script', e.target.value, e.type === 'blur');
            }}
          />
        </Form.Item>
        <Form.Item
          label="跳回话术"
          name="jumpBackScript"
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
          tooltip={{
            overlayStyle: { maxWidth: 280 },
            title: '当流程从问答执行到组件时，会播放该话术；如果不填写，将播放以上话术内容',
            arrowPointAtCenter: true,
            placement: 'bottomLeft',
            icon: <QuestionCircleFilled />,
            className: 'tooltip-icon-blue',
          }}
        >
          <TextArea
            maxLength={500}
            onBlur={(e: { target: { value: any }; type: string }) => {
              onInputChange('jumpBackScript', e.target.value, e.type === 'blur');
            }}
          />
        </Form.Item>
        {/* <Form.Item label="短信设置">
          <Switch
            defaultChecked={selectedData.smsSwitch === 'on'}
            onChange={(status: boolean) => {
              onInputChange('smsSwitch', status ? 'on' : 'off', true);
              if (!status) {
                // 关闭时，需要清空短信模板id
                onInputChange('smsTemplateId', undefined, true);
              }
            }}
          />
        </Form.Item>
        {selectedData.smsSwitch === 'on' && (
          <Form.Item name="smsTemplateId" rules={[{ required: true, message: '请选择短信模板' }]}>
            <PageSelect
              disabled={isView}
              allowClear
              key="smsSelect"
              ref={smsSelectRef}
              fetchData={fetchSmsTempList}
              placeholder="请选择短信模板"
              fetchRecord={fetchSmsTempRecord}
              onChange={(val: any, data: any) => {
                if (!data) {
                  console.log('data无值---赋值更新数据', val, data);
                  onInputChange('smsTemplateId', val, true);
                }
              }}
            />
          </Form.Item>
        )} */}
        <Form.Item label="打断设置">
          <Switch
            defaultChecked={selectedData.breakSwitch === 'on'}
            onChange={(status: any) => {
              onInputChange('breakSwitch', status ? 'on' : 'off', true);
              if (!status) {
                // 关闭时，需要清空规则
                onInputChange('ruleBreak', undefined, true);
              }
            }}
          />
        </Form.Item>
        {selectedData.breakSwitch === 'on' && (
          <Form.Item
            name="ruleBreak"
            getValueFromEvent={event => {
              return event.target.value.replace(/\s+/g, '');
            }}
          >
            <TextArea
              placeholder="请输入打断规则，限500字符以内"
              maxLength={500}
              onBlur={(e: { target: { value: any }; type: string }) => {
                onInputChange('ruleBreak', e.target.value, e.type === 'blur');
              }}
            />
          </Form.Item>
        )}
        <Divider />
        {/* 意图：多选 */}
        <Form.Item
          label="选择意图"
          name="intentionArrayItem"
          rules={[{ required: true, type: 'array', message: '请输入需要关联的意图' }]}
        >
          <AntdSelect
            disabled={isView}
            mode="multiple"
            showSearch
            labelInValue
            placeholder="请输入需要关联的意图"
            getPopupContainer={(triggerNode: { parentElement: any }) => triggerNode.parentElement}
            onDeselect={(item: any) => {
              onRemoveLink('fromPort', item.label, selectedData.key);
            }}
            onBlur={() => {
              // 失焦后设置搜索内容空白, 定时器-避免添加意图时找不到搜索内容
              setTimeout(() => {
                setSearchText('');
              }, 500);
            }}
            onSearch={(text: string) => {
              setCurrent(1);
              setSearchText(text.trim());
            }}
            filterOption={false}
            onChange={(obj: any) => {
              console.log('选择意图修改**', obj);
              /**修改属性名 */
              const newObj = cloneDeep(obj).map((item: any) => {
                return {
                  intentionId: item.value,
                  text: item.label,
                  interfaceInfo: null,
                };
              });
              newObj.forEach((item: any) => {
                intentionArrayItem.forEach((subItem: any) => {
                  if (item.intentionId === subItem.value) {
                    // 接口信息
                    item.interfaceInfo = subItem.interfaceInfo;
                  }
                });
              });
              onInputChange('intentionArray', newObj, true);
            }}
            /**自定义下拉区域 */
            dropdownRender={(menu: any) => (
              <div>
                {menu}
                <Divider style={{ margin: '4px 0' }} />
                <div style={{ padding: '8px', textAlign: 'center' }}>
                  <Pagination
                    simple
                    current={current}
                    total={total}
                    pageSize={pageSize}
                    onChange={current => {
                      setCurrent(current);
                    }}
                  />
                </div>
                <Divider style={{ margin: '4px 0' }} />
                {/* 搜索关键字，添加意图 */}
                {searchText && (
                  <div
                    style={{
                      display: 'flex',
                      flexWrap: 'nowrap',
                      padding: 8,
                      alignItems: 'center',
                    }}
                  >
                    <Input style={{ flex: 'auto' }} value={searchText} bordered={false} readOnly />
                    <Button
                      type="link"
                      style={{
                        flex: 'none',
                        padding: '8px',
                        display: 'block',
                        cursor: 'pointer',
                      }}
                      onClick={() => addItem(searchText)}
                    >
                      <PlusOutlined /> 添加意图
                    </Button>
                  </div>
                )}
              </div>
            )}
          >
            {/* 意图列表-select选项option */}
            {intentionList.map(item => {
              return (
                <Option key={item.intentionId} value={item.intentionId}>
                  {item.intentionName}
                </Option>
              );
            })}
          </AntdSelect>
        </Form.Item>
        {/* 意图-select底部列表: 添加后续接口 */}
        {
          <Row gutter={[0, 10]}>
            {intentionArrayItem.map((item: any, index: number) => {
              return (
                <Col key={item.value} span={24}>
                  <Button
                    type="primary"
                    icon={<SettingOutlined />}
                    onClick={() => {
                      handleClickIntentionItem(index);
                    }}
                  >
                    {item.label}
                  </Button>
                  {/* 点击意图，展示接口相关信息 */}
                  {item.interfaceInfo && (
                    <Row justify="space-between" align="middle">
                      <Col>后续接口:{item.interfaceInfo.name}</Col>
                      <Col>
                        <Button
                          type="link"
                          icon={<EditOutlined />}
                          disabled={isView}
                          onClick={() => {
                            handleClickIntentionItem(index);
                          }}
                        />
                        <Button
                          type="link"
                          icon={<DeleteOutlined />}
                          disabled={isView}
                          onClick={() => {
                            deleteInterfaceInfo(index);
                          }}
                        />
                      </Col>
                    </Row>
                  )}
                </Col>
              );
            })}
          </Row>
        }
        {/* 全局未理解设置 */}
        {selectedData.useGlobalNotUnderstoodSwitch === 'on' && (
          <>
            <Divider />
            <Form.Item
              className="form-list-item-tit"
              label="未理解设置"
              style={{ flexDirection: 'row' }}
            >
              <Button
                className="global-set"
                type="link"
                disabled={isView}
                onClick={() => {
                  // 切换自定义
                  onInputChange('useGlobalNotUnderstoodSwitch', 'off', true);
                }}
              >
                使用自定义设置
              </Button>
            </Form.Item>
            {maxNotUnderstood ? (
              <GlobalNotUnderstood max={maxNotUnderstood} isReadOnly />
            ) : (
              <div className="no-global-set">暂无设置，请到全局设置中配置或自定义设置</div>
            )}
          </>
        )}
        {/* 未理解设置（最多3次） */}
        {selectedData.useGlobalNotUnderstoodSwitch !== 'on' &&
          selectedData.notUnderstoodScriptArray && (
            <>
              <Divider />
              {/* 第1-2次未理解：(话术) */}
              <Form.List name="notUnderstoodScriptArray">
                {(fields, { add, remove }) => (
                  <>
                    <Form.Item
                      className="form-list-item-tit"
                      required
                      label="未理解设置"
                      style={{ flexDirection: 'row' }}
                    >
                      <Tooltip title={fields.length > 1 ? '最多3次未理解设置' : '添加未理解设置'}>
                        <Button
                          type="link"
                          onClick={() => {
                            // 添加未理解话术
                            const arr = cloneDeep(selectedData.notUnderstoodScriptArray);
                            arr.push(undefined);
                            onInputChange('notUnderstoodScriptArray', arr, true);
                            add();
                          }}
                          disabled={isView || fields.length > 1 ? true : false}
                        >
                          <PlusCircleOutlined className="form-list-btn-icon" />
                        </Button>
                      </Tooltip>
                      <Button
                        className="global-set"
                        type="link"
                        onClick={() => {
                          // 切换全局
                          onInputChange('useGlobalNotUnderstoodSwitch', 'on', true);
                        }}
                        disabled={isView}
                      >
                        使用全局设置
                      </Button>
                    </Form.Item>
                    {/* 循环体-内部 */}
                    {fields.map((field, index) => (
                      <div key={field.key} className="form-list-item-wrap unselect-words">
                        <Form.Item
                          {...field}
                          className="form-list-item-ctn"
                          label={`第${index + 1}次未理解，则播放话术`}
                          rules={[
                            {
                              required: true,
                              whitespace: true,
                              max: 500,
                              message: `请输入第${index + 1}次播放话术`,
                            },
                          ]}
                          getValueFromEvent={event => {
                            return event.target.value.replace(/\s+/g, '');
                          }}
                        >
                          <TextArea
                            maxLength={500}
                            placeholder="请输入播放话术"
                            onBlur={(e: { target: { value: any } }) => {
                              const value = e.target.value;
                              const arr = cloneDeep(selectedData.notUnderstoodScriptArray);
                              arr[index] = value;
                              onInputChange('notUnderstoodScriptArray', arr, true);
                            }}
                          />
                        </Form.Item>
                        {!isView && (
                          <Tooltip title="删除设置">
                            <MinusCircleOutlined
                              className="form-list-btn-icon  btn-delete"
                              onClick={() => {
                                const arr = cloneDeep(selectedData.notUnderstoodScriptArray);
                                if (index <= arr.length - 1) {
                                  // 删除的数据，在数组中存在。需要从数组删除，更新数组。
                                  // 更新数据结构
                                  arr.splice(index, 1);
                                  onInputChange('notUnderstoodScriptArray', arr, true);
                                }
                                remove(field.name);
                              }}
                            />
                          </Tooltip>
                        )}
                      </div>
                    ))}
                  </>
                )}
              </Form.List>
              {/* 第3次未理解：节点跳转 */}
              <div className="form-list-last-item unselect-words">
                {
                  <Form.Item
                    name="notUnderstoodFollowUpAct"
                    className="form-list-item-ctn"
                    label={`第${selectedData.notUnderstoodScriptArray?.length + 1}
                    次未理解，则跳转节点`}
                    rules={[
                      {
                        required: true,
                        message: '请选择跳转节点',
                      },
                    ]}
                  >
                    <Select
                      placeholder="请选择跳转节点"
                      allowClear
                      labelInValue
                      getPopupContainer={(triggerNode: { parentElement: any }) =>
                        triggerNode.parentElement
                      }
                      onChange={(obj: any) => {
                        onInputChange('notUnderstoodFollowUpAct', obj, true);
                      }}
                    >
                      {nodeDataArray.map((item: any) => {
                        return (
                          <Option
                            key={'notUnderstoodFollowUpAct_' + item.key}
                            value={item.key}
                            disabled={item.key === 0 || item.key === selectedData.key}
                          >
                            {item.title}
                          </Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                }
              </div>
            </>
          )}

        {/* 全局超时设置 */}
        {selectedData.useGlobalTimeoutSwitch === 'on' && (
          <>
            <Divider />
            <Form.Item
              className="form-list-item-tit"
              label="超时静默设置"
              style={{ flexDirection: 'row' }}
            >
              <Button
                className="global-set"
                type="link"
                disabled={isView}
                onClick={() => {
                  // 切换自定义
                  onInputChange('useGlobalTimeoutSwitch', 'off', true);
                }}
              >
                使用自定义设置
              </Button>
            </Form.Item>
            {maxTimeout ? (
              <GlobalTimeout max={maxTimeout} isReadOnly />
            ) : (
              <div className="no-global-set">暂无设置，请到全局设置中配置或自定义设置</div>
            )}
          </>
        )}
        {/* 超时设置（最多4次）*/}
        {selectedData.useGlobalTimeoutSwitch !== 'on' && selectedData.timeoutScriptArray && (
          <>
            <Divider />
            {/* 第1-3次超时：超时设置(时间、话术) */}
            <Form.List name="timeoutScriptArray">
              {(fields, { add, remove }) => (
                <>
                  <Form.Item
                    className="form-list-item-tit"
                    required
                    label="超时静默设置"
                    style={{ flexDirection: 'row' }}
                  >
                    <Tooltip title={fields.length > 2 ? '最多4次超时设置' : '添加超时设置'}>
                      <Button
                        type="link"
                        onClick={() => {
                          // 添加超时设置
                          const arr = cloneDeep(selectedData.timeoutScriptArray);
                          arr.push({
                            timeout: 5,
                            script: undefined,
                          });
                          onInputChange('timeoutScriptArray', arr, true);
                          add();
                        }}
                        disabled={isView || fields.length > 2 ? true : false}
                      >
                        <PlusCircleOutlined className="form-list-btn-icon" />
                      </Button>
                      <Button
                        className="global-set"
                        type="link"
                        disabled={isView}
                        onClick={() => {
                          // 切换全局
                          onInputChange('useGlobalTimeoutSwitch', 'on', true);
                        }}
                      >
                        使用全局设置
                      </Button>
                    </Tooltip>
                  </Form.Item>
                  {/* 循环体-内部 */}
                  {fields.map((field, index) => (
                    <div key={field.key} className="form-list-item-wrap unselect-words">
                      <Form.Item
                        required
                        label={`第${index + 1}次静默达到`}
                        className="form-list-item-ctn"
                        style={{ flexDirection: 'row' }}
                      >
                        <Form.Item
                          {...field}
                          noStyle
                          name={[field.name, 'timeout']}
                          fieldKey={[field.fieldKey, 'timeout']}
                        >
                          <InputNumber
                            min={1}
                            max={100}
                            precision={0}
                            size="middle"
                            placeholder="1-100"
                            className="timeout-number-input"
                            parser={(value: any) => value || 5}
                            onBlur={(e: { target: { value: any } }) => {
                              const arr = cloneDeep(selectedData.timeoutScriptArray);
                              arr[index].timeout = Number(e.target.value) || 5;
                              onInputChange('timeoutScriptArray', arr, true);
                            }}
                          />
                        </Form.Item>
                        <span className="form-item-last-txt">秒，则播放超时话术</span>
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label=""
                        name={[field.name, 'script']}
                        fieldKey={[field.fieldKey, 'script']}
                        rules={[
                          {
                            required: true,
                            whitespace: true,
                            max: 500,
                            message: `请输入第${index + 1}次超时话术`,
                          },
                        ]}
                        getValueFromEvent={event => {
                          return event.target.value.replace(/\s+/g, '');
                        }}
                      >
                        <TextArea
                          maxLength={500}
                          placeholder="请输入超时话术"
                          onBlur={(e: { target: { value: any } }) => {
                            const value = e.target.value;
                            console.log(value, '超时话术超时话术超时话术');
                            const arr = cloneDeep(selectedData.timeoutScriptArray);
                            arr[index].script = value;
                            onInputChange('timeoutScriptArray', arr, true);
                          }}
                        />
                      </Form.Item>
                      {!isView && (
                        <Tooltip title="删除设置">
                          <MinusCircleOutlined
                            className="form-list-btn-icon  btn-delete"
                            onClick={() => {
                              const arr = cloneDeep(selectedData.timeoutScriptArray);
                              if (index <= arr.length - 1) {
                                // 删除的数据，在数组中存在。需要从数组删除，更新数组。
                                // 更新数据结构
                                arr.splice(index, 1);
                                onInputChange('timeoutScriptArray', arr, true);
                              }
                              remove(field.name);
                            }}
                          />
                        </Tooltip>
                      )}
                    </div>
                  ))}
                </>
              )}
            </Form.List>
            {/* 第4次超时：节点跳转 */}
            <div className="form-list-last-item unselect-words">
              <Form.Item
                required
                className="form-list-item-ctn"
                style={{ flexDirection: 'row' }}
                label={`第${selectedData.timeoutScriptArray?.length + 1}次静默达到`}
              >
                <Form.Item name="timeoutFollowUpStateVal" noStyle>
                  <InputNumber
                    min={1}
                    max={100}
                    precision={0}
                    placeholder="1-100"
                    className="timeout-number-input"
                    parser={(value: any) => value || 5}
                    onBlur={(e: { target: { value: any } }) => {
                      const val = Number(e.target.value) || 5;
                      onInputChange('timeoutFollowUpStateVal', val, true);
                    }}
                  />
                </Form.Item>
                <span className="form-item-last-txt">秒，则跳转节点</span>
              </Form.Item>
              <Form.Item
                name="timeoutFollowUpAct"
                rules={[
                  {
                    required: true,
                    message: '请选择跳转节点',
                  },
                ]}
              >
                <Select
                  placeholder="请选择跳转节点"
                  allowClear
                  labelInValue
                  getPopupContainer={(triggerNode: { parentElement: any }) =>
                    triggerNode.parentElement
                  }
                  onChange={(obj: any) => {
                    onInputChange('timeoutFollowUpAct', obj, true);
                  }}
                >
                  {nodeDataArray.map((item: any) => {
                    return (
                      <Option
                        key={'timeoutFollowUpAct_' + item.key}
                        value={item.key}
                        disabled={item.key === 0}
                      >
                        {item.title}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </div>
          </>
        )}
      </Form>
      <Modal
        title="添加后续接口"
        visible={typeof intentionIndex === 'number'}
        width={420}
        okButtonProps={{ disabled: isView }}
        onOk={() => {
          if (!selectedIntentionName) {
            message.error(`请选择接口`);
            return;
          }
          intentionArrayItem[intentionIndex as number] = intentionContent;
          const newArr = cloneDeep(intentionArrayItem).map((item: any) => {
            return {
              intentionId: item.value,
              text: item.label,
              interfaceInfo: item.interfaceInfo,
            };
          });
          // 更新意图节点数据，包含意图选项对应的接口信息
          onInputChange('intentionArray', newArr, true);
          setIntentionIndex(null);
        }}
        onCancel={() => {
          setIntentionIndex(null);
        }}
      >
        <Spin spinning={selecting}>
          {intentionIndex !== null && (
            <Form form={formInterface}>
              <Form.Item label="调用接口" required>
                <AntdSelect
                  disabled={isView}
                  showSearch
                  placeholder="请选择接口"
                  // labelInValue
                  value={selectedIntentionName}
                  getPopupContainer={(triggerNode: { parentElement: any }) =>
                    triggerNode.parentElement
                  }
                  onSearch={debounce(text => {
                    setCurrentInterface(1);
                    setSearchTextInterface(text.trim());
                  }, 700)}
                  filterOption={false}
                  onChange={(interfaceId: number) => {
                    getInterfaceInfo(interfaceId);
                  }}
                  /**自定义下拉区域 */
                  dropdownRender={(menu: any) => (
                    <div>
                      {menu}
                      {totalInterface > 0 && (
                        <>
                          <Divider style={{ margin: '4px 0' }} />
                          <div style={{ padding: '8px', textAlign: 'center' }}>
                            <Pagination
                              simple
                              current={currentInterface}
                              total={totalInterface}
                              pageSize={pageSizeInterface}
                              onChange={currentInterface => {
                                setCurrentInterface(currentInterface);
                              }}
                            />
                          </div>
                        </>
                      )}
                    </div>
                  )}
                >
                  {/* 接口列表 */}
                  {interfacesList.map(item => {
                    return (
                      <Option key={item.interfaceId} value={item.interfaceId}>
                        {item.interfaceName}
                      </Option>
                    );
                  })}
                </AntdSelect>
              </Form.Item>
              {intentionContent.interfaceInfo && (
                <>
                  <Col style={{ marginBottom: 5 }}>
                    请求方式 {intentionContent.interfaceInfo.method}
                  </Col>
                  <Col style={{ marginBottom: 5 }}>
                    接口地址 {intentionContent.interfaceInfo.url}
                  </Col>
                  {intentionContent.interfaceInfo.requestParam &&
                    intentionContent.interfaceInfo.requestParam.length > 0 && (
                      <>
                        <Row gutter={[0, 10]}>
                          <Col span={12}>请求参数</Col>
                          <Col span={12}>内部参数</Col>
                        </Row>
                        {intentionContent.interfaceInfo.requestParam.map(
                          (item: any, index: number) => {
                            return (
                              <Row gutter={[0, 10]} key={item.key}>
                                <Col span={12}>{item.key}</Col>
                                <Col span={12}>
                                  <Input
                                    value={item.value}
                                    onChange={(e: { target: { value: any } }) => {
                                      intentionContent['interfaceInfo']['requestParam'][index][
                                        'value'
                                      ] = e.target.value;
                                      setIntentionContent({
                                        ...intentionContent,
                                      });
                                    }}
                                  />
                                </Col>
                              </Row>
                            );
                          }
                        )}
                      </>
                    )}
                  {intentionContent.interfaceInfo.responseParam &&
                    intentionContent.interfaceInfo.responseParam.length > 0 && (
                      <>
                        <Row gutter={[0, 10]}>
                          <Col span={12}>返回参数</Col>
                          <Col span={12}>内部参数</Col>
                        </Row>
                        {intentionContent.interfaceInfo.responseParam.map(
                          (item: any, index: number) => {
                            return (
                              <Row gutter={[0, 10]} key={item.key}>
                                <Col span={12}>{item.key}</Col>
                                <Col span={12}>
                                  <Input
                                    value={item.value}
                                    onChange={(e: { target: { value: any } }) => {
                                      intentionContent['interfaceInfo']['responseParam'][index][
                                        'value'
                                      ] = e.target.value;
                                      setIntentionContent({
                                        ...intentionContent,
                                      });
                                    }}
                                  />
                                </Col>
                              </Row>
                            );
                          }
                        )}
                      </>
                    )}
                </>
              )}
            </Form>
          )}
        </Spin>
      </Modal>
    </>
  );
};

export default React.memo(IntentComponent);
